<template>
<div class='page-alloc-menu'>
  <el-card>
    <div slot="header">
      <span>分配权限</span>
    </div>
    <div></div>
    <el-tree
      :data="resources"
      show-checkbox
      :props="defaultProps"
      :default-checked-keys="defaultCheckedKeys"
      :default-expanded-keys="defaultCheckedKeys"
      node-key="id"
      ref="tree"
      default-expand-all>
    </el-tree>
    <el-button type="primary" @click="clearTree">清空</el-button>
    <el-button type="primary" @click="save">保存</el-button>
  </el-card>
</div>
</template>

<script lang='ts'>
import Vue from 'vue'
import {
  getAllResources,
  allocateRoleResources,
  getRoleResources
} from '@/apis/resource'
import { getResourceCategories } from '@/apis/resource-category'
import { Tree } from 'element-ui'
export default Vue.extend({
  props: {
    roleId: {
      type: [String, Number],
      required: true
    }
  },
  data () {
    return {
      getSelectKeys: [],
      defaultCheckedKeys: [],
      resources: [],
      menu: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      }
    }
  },
  created () {
    this.loadResources()
    this.loadRoleResources()
  },
  methods: {
    async loadResources () {
      const ret = await Promise.all([getAllResources(), getResourceCategories()])
      const resources = ret[0].data
      const resourceCategories = ret[1].data
      resources.forEach((r: any) => {
        const category = resourceCategories.find((c: any) => c.id === r.categoryId)
        if (category) {
          category.children = category.children || []
          category.children.push(r)
        }
      })
      // 修改顶层分类 ID：因为分类 ID 和资源 ID 冲突
      resourceCategories.forEach((item: any) => {
        item.id = Math.random()
      })

      this.resources = resourceCategories
    },
    async loadRoleResources () {
      const { data } = await getRoleResources(this.roleId)
      this.getCheckedResources(data)
    },
    getCheckedResources (resources: any) {
      resources.forEach((r: any) => {
        r.resourceList && r.resourceList.forEach((c: any) => {
          if (c.selected) {
            this.defaultCheckedKeys = [...this.defaultCheckedKeys, c.id] as any
          }
        })
      })
    },
    clearTree () {
      (this.$refs.tree as Tree).setCheckedKeys([])
    },
    async save () {
      const checkedNodes = (this.$refs.tree as Tree).getCheckedNodes()
      const resourceIdList: number[] = []
      checkedNodes.forEach(item => {
        if (!item.children) {
          resourceIdList.push(item.id)
        }
      })
      await allocateRoleResources({
        roleId: this.roleId,
        resourceIdList
      })
      this.$message.success('保存成功')
      this.$router.back()
    }
  }
})
</script>

<style lang='scss'>

</style>
